# coding=utf-8
'''
Created on 2012-8-28

@author: quanwei
'''
import MySQLdb
class DbHelper(object):
    conn = None
    
    def getConn(self):
        if self.conn == None:
            self.conn = MySQLdb.connect(host='127.0.0.1', user='root',passwd='111111',charset="utf8")
            cursor = self.conn.cursor()       
            cursor.execute("set autocommit=1")
            cursor.execute("set names utf8")
        
        try:
            cursor = self.conn.cursor()
            cursor.execute("set names utf8")
        except:
            print "reconnect"
            self.conn = MySQLdb.connect(host='127.0.0.1', user='root',passwd='111111')
            cursor = self.conn.cursor()
            cursor.execute("set autocommit=1")
            cursor.execute("set names utf8")
            
        return self.conn
    
    def execute(self,sql):
        
        conn = self.getConn()
        cursor = conn.cursor()           
        print(sql)
        cursor.execute(sql.encode("utf-8"))  
        cursor.close();
        
        
    def fetchAll(self,sql):
        
        conn = self.getConn()
        cursor = conn.cursor(MySQLdb.cursors.DictCursor)           
        print(sql)
        cursor.execute(sql)
        results=cursor.fetchall()
        cursor.close();
        
        return results      
        
    def fetchOne(self,sql):        
        conn = self.getConn()
        cursor = conn.cursor()           
        print(sql)
        cursor.execute(sql)
        results=cursor.fetchall()
        cursor.close();
        
        for r in results:
            return r[0]  
        
    def lastInsertId(self):        
        conn = self.getConn()
        cursor = conn.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute("select last_insert_id() as id")
        results=cursor.fetchall()
        cursor.close();
        
        return int(results[0]['id'])